// ==UserScript==
// @name         允许复制网页所有内容
// @namespace    http://tampermonkey.net/
// @version      2.0
// @description  解除网页内容复制限制，作者：ddjyx
// @author       ddjyx
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 安全地移除阻止默认行为的事件监听器
    function removeCopyRestrictions() {
        const eventNames = ['copy', 'cut', 'paste', 'contextmenu', 'selectstart'];
        document.addEventListener('mouseover', (event) => {
            let target = event.target;
            while (target && target !== document) {
                eventNames.forEach(eventName => {
                    const clone = target.cloneNode(true); // 克隆节点以安全地移除事件
                    target.replaceWith(clone);
                });
                target = target.parentNode;
            }
        }, true);
    }

    // 禁用禁止选择文本的样式
    function disableUserSelectStyles() {
        const css = '* {-webkit-user-select: auto !important; -moz-user-select: auto !important; -ms-user-select: auto !important; user-select: auto !important;}';
        const styleSheet = document.createElement("style");
        styleSheet.type = "text/css";
        styleSheet.textContent = css; // 使用 textContent 代替 innerText
        document.head.appendChild(styleSheet);
    }

    // 处理 iframe 中的内容
    function handleIFrame() {
        const iframes = document.getElementsByTagName('iframe');
        for (let i = 0; i < iframes.length; i++) {
            try {
                const iframeDocument = iframes[i].contentDocument || iframes[i].contentWindow.document;
                if (iframeDocument && iframeDocument.body) {
                    iframeDocument.body.style.userSelect = 'auto';
                }
            } catch (e) {
                console.warn('无法访问跨域 iframe:', e);
            }
        }
    }

    // 监控 DOM 变化以处理动态加载的内容
    function observeDOMChanges() {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.addedNodes.length) {
                    removeCopyRestrictions();
                    disableUserSelectStyles();
                    handleIFrame();
                }
            });
        });

        observer.observe(document.body, { childList: true, subtree: true });
    }

    removeCopyRestrictions();
    disableUserSelectStyles();
    handleIFrame();
    observeDOMChanges();

})();